//補充
/**
* 更换EasyUI主题的方法
* @param themeName
* 主题名称
*/
//切换主题
function ChangeTheme(themeName) {
    //以下代码段根据前台的easyuiTheme来取得easyui的路径
    var $easyuiTheme = $('#easyuiTheme');
    var url = $easyuiTheme.attr('href');
    var href = url.substring(0, url.indexOf('themes')) + 'themes/' + themeName + '/easyui.css';
    $easyuiTheme.attr('href', href);
    //递归子iframe，将其主题也一同切换
    var $iframe = $('iframe');
    if ($iframe.length > 0) {
        for (var i = 0; i < $iframe.length; i++) {
            var ifr = $iframe[i];
            $(ifr).contents().find('#easyuiTheme').attr('href', href);
        }
    }
    $.cookie('easyuiThemeName', themeName, { expires: 7 });
};

if ($.cookie('easyuiThemeName')) {
    ChangeTheme($.cookie('easyuiThemeName'));
}

$.extend({
    //载入嵌入页面
    LoadEmbed: function (divName, href) {
        $(divName).panel({
            href: href
        });
    },

    //写入等待
    ShowMask: function () {
        var body = $("body").eq(0);
        var mask = $("<div class=\"datagrid-mask\" style=\"display:block; z-index:77777;\"></div>").appendTo(body);
        var img = $("<img class=\"datagrid-mask-img\" src='/Res/images/loading.gif' style=\"z-index:88888;\" />");
        img.css("left", (body.width() - 214) / 2).css("top", 12).css("position", "absolute").appendTo(body);
    },
    //移除等待
    HideMask: function () {
        var body = $("body").eq(0);
        body.children("div.datagrid-mask").remove();
        body.children("img.datagrid-mask-img").remove();
    },
    //Api路径
    Api: function (path) {
        return "../public/ApiHandler.ashx?path=" + path;
    },
    //Ajax遮罩
    AjaxMask: function (options) {
        $.ajax({
            url: options.url, type: options.type,
            data: options.data, success: options.success,
            beforeSend: function () { $.ShowMask(); },
            complete: function () { $.HideMask(); },
            error: function (request, status, thrown) { $.Error(request.responseText); }
        });
    },
    //报错
    Error: function (html) {
        html = String(html).replace(/<style[^>]*?>[\s\S]*?<\/style>/, '');
        html = html.replace(/<meta[^>]*?>[\s\S]*?>/, '');
        html = html.replace(/<title[^>]*?>[\s\S]*?<\/title>/, '');
        html = $("<div style='padding:15px;'>" + html + "</div>");

        $.AdjustmentDialog($.ModelDialog({ title: "错误", width: 600, content: html.show() }));
    },
    //刷新列表
    DataGridReload: function (value) {
        $(value).datagrid("reload");
        $(value).datagrid("clearChecked");
    },
    //刷新树表
    TreeGridReload: function (value) {
        $(value).treegrid("reload");
        $(value).treegrid("unselectAll");
    },
    //展开节点
    TreeGridExpandAll: function (value) {
        $(value).treegrid("expandAll");
    },
    //收起节点
    TreeGridCollapseAll: function (value) {
        $(value).treegrid("collapseAll");
    },
    //树形全选
    TreeCheckAll: function (value) {
        var nodes = $(value).tree("getChecked", "unchecked");
        for (var i = 0; i < nodes.length; i++) { $(value).tree("check", nodes[i].target); }
    },
    //取消选择
    TreeUnCheckAll: function (value) {
        var nodes = $(value).tree("getChecked");
        for (var i = 0; i < nodes.length; i++) { $(value).tree("uncheck", nodes[i].target); }
    },
    //提示信息
    EasyuiMsg: function (content) {
        $.messager.alert("提示", content, "info");
    },
    //浮出信息
    EasyuiSlide: function (content) {
        $.messager.show({ title: "提示", msg: content });
    },
    //确认提示
    EasyuiConfirm: function (content, handler) {
        $.messager.confirm("提示", content, handler);
    },
    //获取图标
    GetIcon: function (value) {
        return "<span class='list-span " + value + "'></span>";
    },
    //获取按钮
    GetIconButton: function (value, text, fun) {
        var span = "<span class='l-btn-text " + value + " l-btn-icon-left'>" + text + "</span>";
        var spanbox = "<span class='l-btn-left'>" + span + "</span>";
        return "<a class='list-link' href='javascript:void(0)' onclick='" + fun + "'>" + spanbox + "</a>";
    },
    //获取播放器
    GetDewplayer: function (file, span) {
        var player = $("<div />");
        player.html('<embed src="../public/dewplayer/dewplayer.swf?mp3=' + file + '"' +
                        'type="application/x-shockwave-flash"' +
                        'bgcolor="#ffffff" quality="high" wmode="transparent"' +
                        'allowfullscreen="true" allowscriptaccess="always" width="200" height="20"' +
                        'pluginspage="http://www.macromedia.com/go/getflashplayer" />');
        if (($.browser.msie && Number($.browser.version) < 8) || !span) { return player.html(); }
        else { return "<span style='display:inline-block; height:20px;vertical-align:middle;'>" + player.html() + "</span>"; }
    },
    //获取是否
    GetYesOrNo: function (value) {
        if (value) {
            return $.GetIcon("icon-bullet_tick");
        }
        else {
            return $.GetIcon("icon-bullet_minus");
        }
    },
    //获取是否
    GetYesOrNoData: function () {
        return {
            editable: false, required: true,
            width: 150, panelHeight: "auto",
            data: [
                { value: "True", text: "是" },
                { value: "False", text: "否" }
            ]
        };
    },
    //实体窗口
    ModelDialog: function (options) {
        if (options.dialogid) {
            options.dialogid = "id='" + options.dialogid + "'";
        }
        var buttons = [];
        if (!options.width) { options.width = "auto"; }
        if (!options.height) { options.height = "auto"; }

        if (options.handler) { buttons.push({ text: "确定", iconCls: "icon-ok", handler: options.handler }); }
        buttons.push({ text: "关闭", iconCls: "icon-no", handler: function () { $.ButtonCloseDialog(this); } });

        var dialog = $("<div " + options.dialogid + " style='z-index:1000;' />").dialog({

            title: options.title, href: options.href,
            width: options.width, height: options.height,
            toolbar: options.toolbar, content: options.content,
            modal: true, cache: false, collapsible: true,  //允许折叠？
            maximizable: options.maximizable,  //允许最大化
            maximized: options.maximized,  //初始是否要最大化
            buttons: buttons, iconCls: options.iconCls,
            onLoad: function () {
                options.onLoad(); $.AdjustmentDialog(dialog);
            },
            onClose: function () { $(this).dialog("destroy"); }
        });
        return dialog;
    },

    //调整位置
    AdjustmentDialog: function (dialog) {
        var boxheight = $(dialog).parent().height();
        if (boxheight > $(window).height() - 20) {
            dialog.dialog("resize", {
                height: $(window).height() - 20
            });
            $(dialog).parent().next().height($(window).height() - 20);
        }
        else { $(dialog).parent().next().height(boxheight + 12); }
        dialog.dialog("center");
    },
    //关闭窗口
    ButtonCloseDialog: function (button) {
        $(button).closest(".window-body").dialog("destroy");
    },
    //表单实体
    ModelForm: function (options) {
        var submit = function () {
            var bool = $(this).form("validate");
            //if (options.editor) {
            //    KindEditor.sync(options.editor);
            //}
            if (bool) bool = options.validate;
            if (bool) $.ShowMask(); return bool;
        }
        $(options.id).form("submit", {
            url: options.url, onSubmit: submit,
            success: function (result) {
                $.HideMask();
                try {
                    result = JSON.parse(result);
                    if (result.ResultType == 0) {  //ResultType是在OperationResultType定义的，0表示Success成功
                        $.EasyuiSlide(result.Message);  //弹出右下角提示
                        options.success(result);
                        $.ButtonCloseDialog(options.button);
                    }
                    else {
                        $.EasyuiMsg(result.Message);  //弹出提示窗体
                    }
                } catch (e) { $.Error(result); }
            }
        });
    },

    //字典下拉列表
    //controlName：comboBox控件名称（带#）
    //typeTag：字典类型的Tag
    //isAdd：是否新增（新增的时候传入这个参数，编辑不需要）
    //valueField：值对应的字段（若不传则默认为DictionaryName）
    //textField：显示对应的字段（若不传则默认为DictionaryName）
    DictionaryComboList: function (controlName, typeTag, isAdd, valueField, textField) {
        $(controlName).combobox({
            width: 153, panelHeight: "auto",
            url: "/Dictionary/GetDictionaryByTypeTag?typeTag=" + typeTag,
            valueField: valueField === undefined ? "DictionaryName" : valueField,
            textField: textField === undefined ? "DictionaryName" : textField,
            editable: false,
            //如果是新增，则让下拉框默认选中第一个
            onLoadSuccess: function () {
                if (isAdd) {
                    var data = $(controlName).combobox('getData');
                    if (data.length > 0) {
                        $(controlName).combobox('select', data[0][valueField === undefined ? "DictionaryName" : valueField]);
                    }
                }
            }
        });
    },

    //获取地址栏参数
    ///Document/DocumentList?InstanceID=681764fd-aef8-4dcf-84bd-a2d700ffc9a0&Tag=Test
    Request: function (name) {
        var url = location.search; //获取url中"?"符后的字串
        var theRequest = new Object();
        if (url.indexOf("?") != -1) {
            var str = url.substr(1);
            strs = str.split("&");
            for (var i = 0; i < strs.length; i++) {
                theRequest[strs[i].split("=")[0]] = unescape(strs[i].split("=")[1]);
            }
        }
        return theRequest[name];
    },

    //上传文件
    //UploadFile: function (instanceID, tag) {
    //    //var editor = new baidu.editor.ui.Editor({
    //    //    UEDITOR_HOME_URL: '/Res/ueditor/',//配置编辑器路径
    //    //    iframeCssUrl: '/Res/ueditor/themes/iframe.css',//样式路径
    //    //});

    //    //editor.ready(function () {
    //    //    //设置编辑器不可用
    //    //    editor.setDisabled();
    //    //    //隐藏编辑器，因为不会用到这个编辑器实例，所以要隐藏
    //    //    editor.hide();

    //    //    //侦听文件上传，取上传文件列表中第一个上传的文件的路径
    //    //    editor.addListener('afterUpfile', function (t, arg) {
    //    //        //$("#file").attr("value", editor.options.filePath + arg[0].url);
    //    //        //$.messager.show({ title: "提示", msg: editor.options.filePath + arg[0].url });
    //    //        $.messager.alert("提示", editor.options.filePath + arg[0].url, "info");
    //    //    });
    //    //});

    //    ////var myFiles = editor.getDialog("attachment");
    //    ////var myFiles = editor.getDialog('edittd');
    //    ////myFiles.open();

    //    //var dialog = editor.getDialog("insertimage");
    //    //dialog.open();   //打开dialog
    //    //dialog.close();  //关闭dialog

    //    //重新实例化一个编辑器，防止在上面的editor编辑器中显示上传的图片或者文件
    //    var _editor = UE.getEditor('upload_ue');
    //    _editor.ready(function () {
    //        //设置编辑器不可用
    //        _editor.setDisabled();
    //        //隐藏编辑器，因为不会用到这个编辑器实例，所以要隐藏
    //        _editor.hide();
    //        ////侦听图片上传
    //        //_editor.addListener('beforeInsertImage', function (t, arg) {
    //        //    //将地址赋值给相应的input,只去第一张图片的路径
    //        //    $("#picture").attr("value", arg[0].src);
    //        //    //图片预览
    //        //    $("#preview").attr("src", arg[0].src);
    //        //})
    //        //侦听文件上传，取上传文件列表中第一个上传的文件的路径
    //        //_editor.addListener('afterUpfile', function (t, arg) {
    //        //    //$("#file").attr("value", _editor.options.filePath + arg[0].url);
    //        //    //$.EasyuiSlide(_editor.options.filePath + arg[0].url);
    //        //    $.EasyuiSlide("upload Finished");
    //        //})

    //        //侦听文件上传，取上传文件列表中第一个上传的文件的路径
    //        _editor.addListener('afterUpfile', function (t, arg) {
    //            $("#file").attr("value", _editor.options.filePath + arg[0].url);
    //            //$("#file").attr("value", "upload ok");
    //            //$.messager.alert("提示", "upload ok", "info");
    //        })
    //    });
    //    var myFiles = _editor.getDialog("attachment");
    //    myFiles.open();
    //},

    Upload: function (instanceID, tag, btnDisabled) {
        $.UploadMutual("附件操作", "/Document/DocumentList?instanceID=" + instanceID + "&tag=" + tag + "&btnDisabled=" + btnDisabled, instanceID, tag);
    },

    //实体操作
    UploadMutual: function (title, href, instanceID, tag) {
        $.ModelDialog({
            dialogid: "uploadDialog",
            title: title, href: href, width: 650,
            handler: function () {
                $.ModelForm({
                    validate: true, button: $(this),
                    id: "#doc-model",
                    url: "/Document/SavePost",
                    success: function (result) {
                        //保存文件列表
                        var data = $('#documentGrid').datagrid('getRows');  //取得所有数据
                        //Modify By Luozx 2014-02-14：此处需要补充属性
                        if (data != null && data.length > 0) {
                            var dataJson = JSON.stringify(data);
                            var effectRow = new Object();
                            effectRow["Data"] = dataJson;
                            $.post("/Document/SaveDocumentPost?instanceID=" + instanceID + "&tag=" + tag, effectRow, function (saveResult) {  //result.AppendData为返回的对象
                                try {
                                    saveResult = JSON.parse(saveResult);
                                    if (saveResult.ResultType == 0) {  //ResultType是在OperationResultType定义的，0表示Success成功
                                        $.EasyuiSlide(saveResult.Message);  //弹出右下角提示
                                    }
                                    else {
                                        $.EasyuiMsg(saveResult.Message);  //弹出提示窗体
                                    }
                                } catch (e) { $.Error(saveResult); }
                            });
                        }
                    }
                });
            },
            onLoad: function () {
                //BidInfo.FormInit(isAdd);
            }
        });
    },

    ////编辑器初始化（KindEditor-废弃）
    //EditorInit: function (textid, height, lingtag, filterMode, childrenPath) {
    //    var editorkey = KindEditor.create(textid, {
    //        uploadJson: "/Common/UploadFile?childrenPath=" + (childrenPath === undefined ? "" : childrenPath),
    //        fileManagerJson: "/Common/ManageFile",
    //        width: "auto", height: height, allowFileManager: true,
    //        newlineTag: lingtag, filterMode: filterMode, resizeType: 0,
    //        items: [
    //            'source', '|', 'undo', 'redo', '|', 'preview', 'print', 'template', 'code', 'cut', 'copy', 'paste',
    //            'plainpaste', 'wordpaste', '|', 'justifyleft', 'justifycenter', 'justifyright',
    //            'justifyfull', 'insertorderedlist', 'insertunorderedlist', 'indent', 'outdent', 'subscript',
    //            'superscript', 'clearhtml', 'quickformat', 'selectall', '/',
    //            'formatblock', 'fontname', 'fontsize', '|', 'forecolor', 'hilitecolor', 'bold',
    //            'italic', 'underline', 'strikethrough', 'lineheight', 'removeformat', '|', 'image', 'multiimage',
    //            'flash', 'media', 'insertfile', 'table', 'hr', 'emoticons', 'baidumap', 'pagebreak',
    //            'anchor', 'link', 'unlink'
    //        ]
    //    });
    //    prettyPrint(); return editorkey;
    //},
    ////迷你编辑器初始化
    //MiniEditorInit: function (textid, height, lingtag, filterMode, childrenPath) {
    //    debugger;
    //    var editorkey = KindEditor.create(textid, {
    //        uploadJson: "/Common/UploadFile?childrenPath=" + (childrenPath === undefined ? "" : childrenPath),
    //        fileManagerJson: "/Common/ManageFile",
    //        width: 'auto', height: height, allowFileManager: true,
    //        newlineTag: lingtag, filterMode: filterMode, resizeType: 0,
    //        items: [
    //            'source', '|', 'justifyleft', 'justifycenter', 'justifyright',
    //            'justifyfull', '|', 'fontsize', 'forecolor', 'hilitecolor', 'bold',
    //            'italic', 'underline', 'strikethrough', 'lineheight', '|', 'link', 'unlink'
    //        ]
    //    });
    //    prettyPrint(); return editorkey;
    //},

    //MiniUEditor编辑器初始化（需完善，可参考MiniUEditorInit）
    UEditorInit: function (textid, width, height) {
        var editor = new baidu.editor.ui.Editor({
            UEDITOR_HOME_URL: '/Res/ueditor/',//配置编辑器路径
            iframeCssUrl: '/Res/ueditor/themes/iframe.css',//样式路径
            //fileUrl: '/Res/ueditor/net/fileUp.ashx',
            //filePath: '/Res/ueditor/net/',
            //imageUrl: '/Res/ueditor/net/imageUp.ashx',
            //imagePath: '/Res/ueditor/net/',
            //initialContent: '请在此处输入内容...',//初始化编辑器内容
            autoHeightEnabled: false,//高度自动增长
            initialFrameWidth: width === undefined ? 1000 : width,  //初始化编辑器宽度,默认1000
            initialFrameHeight: height === undefined ? 400 : height  //初始化编辑器高度,默认400
        });
        editor.render(textid);
    },

    //MiniUEditor编辑器初始化，参数：
    //instanceID：记录实例ID
    //attachmentTag：附件Tag
    //textid：富文本编辑器ID
    //width：宽度
    //height：高度
    //readonly：只读
    MiniUEditorInit: function (instanceID, attachmentTag, textid, width, height, readonly) {
        var editor = new baidu.editor.ui.Editor({
            UEDITOR_HOME_URL: '/Res/ueditor/',//配置编辑器路径
            iframeCssUrl: '/Res/ueditor/themes/iframe.css',//样式路径
            //fileUrl: '/Res/ueditor/net/fileUp.ashx',
            //filePath: '/Res/ueditor/net/',
            //imageUrl: '/Res/ueditor/net/imageUp.ashx',
            //imagePath: '/Res/ueditor/net/',
            //initialContent: '请在此处输入内容...',//初始化编辑器内容
            autoHeightEnabled: false,//高度自动增长
            initialFrameWidth: width === undefined ? 1000 : width,  //初始化编辑器宽度,默认1000
            initialFrameHeight: height === undefined ? 400 : height,  //初始化编辑器高度,默认400
            readonly: readonly === undefined ? false : readonly,
            toolbars: [['fullscreen', "source", "undo", "redo", "bold", "italic", "underline", "strikethrough", '|', "insertimage", "insertvideo", "attachment", '|', "forecolor", "backcolor", "removeformat", "insertunorderedlist", "insertorderedlist"],
                ["fontfamily", "fontsize", "justifyleft", "justifycenter", "justifyright", "justifyjustify", '|', "link", "unlink", "horizontal", "inserttable", "drafts", "preview"]]
        });
        editor.render(textid);

        //Add By Luozx：侦听文件上传：需要将上传的文件信息添加到DocumentInfo表中，用于系统全局的文档管理
        editor.addListener('afterUpfile', function (t, arg) {
            //debugger;
            //for (var i = 0; i < arg.length; i++) {
            //    //$('#documentGrid').datagrid('appendRow', {
            //    //    FileName: arg[i].original,
            //    //    FilePath: arg[i].url,
            //    //    FileSize: arg[i].fileSize,
            //    //    UploadUser: arg[i].uploadUser,
            //    //    UploadTime: arg[i].uploadTime
            //    //});

            //    $.messager.alert("提示", arg[i].original + arg[i].url + arg[i].fileSize + arg[i].uploadUser + arg[i].uploadTime, "info");
            //}

            if (arg != null && arg.length > 0) {
                var dataJson = JSON.stringify(arg);
                var effectRow = new Object();
                effectRow["Data"] = dataJson;
                //$.post("/Document/SaveRichTextBoxDocumentPost?instanceID=" + instanceID + "&tag=" + tag, effectRow, function (saveResult) {  //result.AppendData为返回的对象
                $.post("/Document/SaveRichTextBoxDocumentPost?instanceID=" + instanceID + "&attachmentTag=" + attachmentTag, effectRow, function (saveResult) {  //result.AppendData为返回的对象
                    try {
                        saveResult = JSON.parse(saveResult);
                        if (saveResult.ResultType == 0) {  //ResultType是在OperationResultType定义的，0表示Success成功
                            $.EasyuiSlide(saveResult.Message);  //弹出右下角提示
                        }
                        else {
                            $.EasyuiMsg(saveResult.Message);  //弹出提示窗体
                        }
                    } catch (e) { $.Error(saveResult); }
                });
            }
        })
    },

    //移除数组元素
    RemoveElement: function (array, element) {
        var index = array.indexOf(element);
        if (index >= 0) {
            array.splice(index, 1);
        }
        return array;
    },

    //创建新的Guid
    NewGuid: function () {
        var s = [];
        var hexDigits = "0123456789abcdef";
        for (var i = 0; i < 36; i++) {
            s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
        }
        s[14] = "4";  // bits 12-15 of the time_hi_and_version field to 0010
        s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1);  // bits 6-7 of the clock_seq_hi_and_reserved to 01
        s[8] = s[13] = s[18] = s[23] = "-";

        var uuid = s.join("");
        return uuid;
    }
});
